import axios from 'axios';
import type { 
  User, 
  Role, 
  Permission, 
  Menu, 
  PaymentOrder, 
  ApiResponse, 
  PaginatedResponse,
  QueryParams,
  SystemMetrics,
  Script,
  ScriptExecution,
  CreateScriptRequest,
  UpdateScriptRequest,
  ExecuteScriptRequest
} from '@/types';

const API_PREFIX = '/api';

// 创建axios实例
const request = axios.create({
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
request.interceptors.response.use(
  (response) => response.data,
  (error) => {
    // 如果是401错误，清除token并跳转到登录页
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/user/login';
    }
    return Promise.reject(error);
  }
);

// 认证相关API
export const authApi = {
  login: (params: { username: string; password: string }) =>
    request.post<ApiResponse<{ token: string; user: User }>>(`${API_PREFIX}/auth/login`, params),

  register: (params: { username: string; email: string; password: string }) =>
    request.post<ApiResponse<User>>(`${API_PREFIX}/auth/register`, params),

  getCurrentUser: () =>
    request.get<ApiResponse<User>>(`${API_PREFIX}/auth/me`),

  getUserMenus: () =>
    request.get(`${API_PREFIX}/auth/menus`),

  getUserPermissions: () =>
    request.get(`${API_PREFIX}/auth/permissions`),

  refreshToken: () =>
    request.post<ApiResponse<{ token: string }>>(`${API_PREFIX}/auth/refresh`),
};

// 用户管理API
export const userApi = {
  getUsers: (params?: QueryParams) =>
    request.get(`${API_PREFIX}/users`, { params }),

  getUserById: (id: number) =>
    request.get(`${API_PREFIX}/users/${id}`),

  createUser: (data: Partial<User>) =>
    request.post(`${API_PREFIX}/users`, data),

  updateUser: (id: number, data: Partial<User>) =>
    request.patch(`${API_PREFIX}/users/${id}`, data),

  deleteUser: (id: number) =>
    request.delete(`${API_PREFIX}/users/${id}`),

  assignRoles: (id: number, roleIds: number[]) =>
    request.post(`${API_PREFIX}/users/${id}/roles`, { roleIds }),
};

// 角色管理API
export const roleApi = {
  getRoles: (params?: QueryParams) =>
    request.get(`${API_PREFIX}/roles`, { params }),

  getRoleById: (id: number) =>
    request.get(`${API_PREFIX}/roles/${id}`),

  createRole: (data: Partial<Role>) =>
    request.post(`${API_PREFIX}/roles`, data),

  updateRole: (id: number, data: Partial<Role>) =>
    request.patch(`${API_PREFIX}/roles/${id}`, data),

  deleteRole: (id: number) =>
    request.delete(`${API_PREFIX}/roles/${id}`),

  assignPermissions: (id: number, permissionIds: number[]) =>
    request.post(`${API_PREFIX}/roles/${id}/permissions`, { permissionIds }),

  assignMenus: (id: number, menuIds: number[]) =>
    request.post(`${API_PREFIX}/roles/${id}/menus`, { menuIds }),
};

// 权限管理API
export const permissionApi = {
  getPermissions: (params?: QueryParams) =>
    request.get(`${API_PREFIX}/permissions`, { params }),

  getPermissionById: (id: number) =>
    request.get(`${API_PREFIX}/permissions/${id}`),

  createPermission: (data: Partial<Permission>) =>
    request.post(`${API_PREFIX}/permissions`, data),

  updatePermission: (id: number, data: Partial<Permission>) =>
    request.patch(`${API_PREFIX}/permissions/${id}`, data),

  deletePermission: (id: number) =>
    request.delete(`${API_PREFIX}/permissions/${id}`),
};

// 菜单管理API
export const menuApi = {
  getMenus: (params?: QueryParams) =>
    request.get(`${API_PREFIX}/menus`, { params }),

  getMenuTree: () =>
    request.get(`${API_PREFIX}/menus/tree`),

  getMenuById: (id: number) =>
    request.get(`${API_PREFIX}/menus/${id}`),

  createMenu: (data: Partial<Menu>) =>
    request.post(`${API_PREFIX}/menus`, data),

  updateMenu: (id: number, data: Partial<Menu>) =>
    request.patch(`${API_PREFIX}/menus/${id}`, data),

  deleteMenu: (id: number) =>
    request.delete(`${API_PREFIX}/menus/${id}`),
};

// 支付管理API
export const paymentApi = {
  getOrders: (params?: QueryParams) =>
    request<ApiResponse<PaginatedResponse<PaymentOrder>>>(`${API_PREFIX}/payment/orders`, {
      params,
    }),

  createOrder: (data: { amount: number; paymentMethod: string }) =>
    request<ApiResponse<PaymentOrder>>(`${API_PREFIX}/payment/orders`, {
      method: 'POST',
      data,
    }),

  getOrderById: (id: number) =>
    request<ApiResponse<PaymentOrder>>(`${API_PREFIX}/payment/orders/${id}`),
};

// 报表数据API
export const reportApi = {
  getUserStats: (dateRange: [string, string]) =>
    request<ApiResponse<any>>(`${API_PREFIX}/reports/user-stats`, {
      params: { startDate: dateRange[0], endDate: dateRange[1] },
    }),

  getPaymentStats: (dateRange: [string, string]) =>
    request<ApiResponse<any>>(`${API_PREFIX}/reports/payment-stats`, {
      params: { startDate: dateRange[0], endDate: dateRange[1] },
    }),

  exportReport: (type: string, params: any) =>
    request(`${API_PREFIX}/reports/export/${type}`, {
      method: 'POST',
      data: params,
      responseType: 'blob',
    }),
};

// 监控数据API
export const monitorApi = {
  getSystemMetrics: () =>
    request.get(`${API_PREFIX}/monitor/system`),

  getMetricsHistory: (duration?: string) =>
    request.get(`${API_PREFIX}/monitor/history`, {
      params: { duration },
    }),

  getSystemInfo: () =>
    request.get(`${API_PREFIX}/monitor/system-info`),

  getApplicationMetrics: () =>
    request.get(`${API_PREFIX}/monitor/application`),

  getHealthCheck: () =>
    request.get(`${API_PREFIX}/monitor/health`),

  getLogAnalysis: () =>
    request.get(`${API_PREFIX}/monitor/logs`),
};

// 脚本管理API
export const scriptApi = {
  getScripts: (params?: { page?: number; pageSize?: number; name?: string; type?: 'node' | 'python'; status?: string }) =>
    request.get<ApiResponse<PaginatedResponse<Script>>>(`${API_PREFIX}/scripts`, { params }),

  getScriptById: (id: number) =>
    request.get<ApiResponse<Script>>(`${API_PREFIX}/scripts/${id}`),

  createScript: (data: CreateScriptRequest) =>
    request.post<ApiResponse<Script>>(`${API_PREFIX}/scripts`, data),

  updateScript: (id: number, data: UpdateScriptRequest) =>
    request.patch<ApiResponse<Script>>(`${API_PREFIX}/scripts/${id}`, data),

  deleteScript: (id: number) =>
    request.delete<ApiResponse<void>>(`${API_PREFIX}/scripts/${id}`),

  executeScript: (id: number, data?: ExecuteScriptRequest) =>
    request.post<ApiResponse<ScriptExecution>>(`${API_PREFIX}/scripts/${id}/execute`, data),

  getScriptExecutions: (scriptId: number, params?: { page?: number; pageSize?: number }) =>
    request.get<ApiResponse<PaginatedResponse<ScriptExecution>>>(`${API_PREFIX}/scripts/${scriptId}/executions`, { params }),

  getExecutionById: (id: number) =>
    request.get<ApiResponse<ScriptExecution>>(`${API_PREFIX}/scripts/executions/${id}`),

  getScriptParameters: (id: number) =>
    request.get<ApiResponse<Array<{ name: string; defaultValue: string; description?: string }>>>(`${API_PREFIX}/scripts/${id}/parameters`),
};

// 通用 API 对象，用于直接 HTTP 请求
export const api = request;